﻿using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;

namespace Office.Automatic.Core.Database
{
    internal class DatabaseContext: DbContext
    {
        private static volatile bool _databaseInitialized = false;
        private static readonly string ConnectionString= new SqliteConnectionStringBuilder()
            { DataSource = "file:memdb1?mode=memory&cache=shared", ForeignKeys = true }.ConnectionString;

        private static readonly SqliteConnection PersistentDbConnection = new SqliteConnection();

        public static void BackupDatabase(string path)
        {
            var connection = new SqliteConnection(new SqliteConnectionStringBuilder()
                { DataSource = path }.ConnectionString);
            connection.Open();

            PersistentDbConnection.BackupDatabase(connection);

            connection.Close();
            connection.Dispose();
        }

        public static void Initialize(string? backupDatabasePath=null)
        {
            if (_databaseInitialized == false)
            {
                PersistentDbConnection.ConnectionString = ConnectionString;
                PersistentDbConnection.Open();
                _databaseInitialized = true;

                if (backupDatabasePath != null)
                {
                    using (var conn = new SqliteConnection(new SqliteConnectionStringBuilder()
                               { DataSource = backupDatabasePath }.ConnectionString))
                    {
                        conn.Open();
                        conn.BackupDatabase(PersistentDbConnection);
                        conn.Close();
                    }
                }
            }
        }
        

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite(ConnectionString);

            base.OnConfiguring(optionsBuilder);

        }
        
    }
}
